<template>
  <div>
    <div class="TrT-container">
      <el-collapse v-model="showPanel" >
        <el-collapse-item  name="1" >
          <template slot="title">
            <div class="myHead">单项读写</div>
          </template>
          <div style="margin:10px">
            <el-row :gutter="1" class="form">
              <!-- 工具栏 -->
              <el-col :span="24">
                <el-button type="primary" icon="el-icon-success">保存</el-button>
              </el-col>
            </el-row>
            <el-row :gutter="1" class="form">
              <!-- r 编写 -->
              <el-col :span="12">
                请求变量名称
                <el-input placeholder="Name" v-model="row.r.name"  :disabled="loading || checking">
                </el-input>
              </el-col>
              <!-- q 编写  -->
              <el-col :span="12">
                反馈变量名称
               <el-input placeholder="Name" v-model="row.q.name" :disabled="loading || checking">
              </el-input>
              </el-col>
            </el-row>
            <el-row :gutter="1" class="form">
              <!-- r 编写 -->
              <el-col :span="12">
                请求变量地址
                <el-input placeholder="地址" v-model="row.r.addr"  :disabled="loading || checking">
                </el-input>
              </el-col>
              <!-- q 编写  -->
              <el-col :span="12">
                反馈变量地址
                <el-input placeholder="地址" v-model="row.q.addr" :disabled="loading || checking">
                </el-input>
              </el-col>
            </el-row>
            <el-row :gutter="1" class="form">
              <!-- r 编写 -->
              <el-col :span="12">
                请求变量长度
                <el-input placeholder="4" v-model="row.r.len"  :disabled="loading || checking">
                </el-input>
              </el-col>
              <!-- q 编写  -->
              <el-col :span="12">
                反馈变量长度
                <el-input placeholder="4" v-model="row.q.len" :disabled="loading || checking">
                </el-input>
              </el-col>
            </el-row>
            <el-row :gutter="1" class="form">
              <!-- r 编写 -->
              <el-col :span="12">
                请求变量类型
                <el-input placeholder="类型" v-model="row.r.type"  :disabled="loading || checking">
                </el-input>
              </el-col>
              <!-- q 编写  -->
              <el-col :span="12">
                反馈变量类型
                <el-input placeholder="类型" v-model="row.q.type" :disabled="loading || checking">
                </el-input>
              </el-col>
            </el-row>
            <el-row :gutter="1" class="form">
              <!-- r 编写 -->
              <el-col :span="12">
                请求起始地址
                <el-input placeholder="地址" v-model="row.r.addrHead"  :disabled="loading || checking">
                </el-input>
              </el-col>
              <!-- q 编写  -->
              <el-col :span="12">
                反馈起始地址
                <el-input placeholder="地址" v-model="row.q.addrHead" :disabled="loading || checking">
                </el-input>
              </el-col>
            </el-row>
            <el-row :gutter="1" class="form">
              <!-- r 编写 -->
              <el-col :span="12">
                请求批量数量
                <el-input placeholder="100" v-model="row.r.addrNum"  :disabled="loading || checking">
                </el-input>
              </el-col>
              <!-- q 编写  -->
              <el-col :span="12">
                反馈批量数量
                <el-input placeholder="100" v-model="row.q.addrNum" :disabled="loading || checking">
                </el-input>
              </el-col>
            </el-row>
          </div>
        </el-collapse-item>
        <el-collapse-item name="2">
          <template slot="title">
            <div class="myHead">多项请求</div>
          </template>
          <!-- rs qs 编写  -->
          <!-- rs   -->
          <el-row :gutter="1" class="form">
            <el-col :span="24">
              <div style="margin:10px;">
                地址/名称/备注:
                <el-input placeholder="地/名称/备注" v-model="requestParamsObjOfRS.name" @keyup.enter="getData" :disabled="loading || checking"> </el-input>
              </div>
            </el-col>
          </el-row>
          <TableOperationButtons style="margin:10px;" :loading="loading" :newButton="newButton"
            :deleteButton="deleteButton" :testButton="testButton"
            improtUrl="/svid/importCSV" exportUrl="/svid/exportCSV" improtUrlDisabled exportUrlDisabled>
          </TableOperationButtons>
          <el-alert :title="alertTitle" type="info" show-icon v-show="alertTitle">
          </el-alert>
          <vxe-table keep-source border resizable show-overflow ref="xTable1" class="vxe-table" empty-text="没有更多数据了！"
          :scroll-y="{ enabled: false }" :loading="loading" :data="tableDataOfRS"
          :sort-config="{trigger: 'cell',showIcon: true, defaultSort: {field: 'id', order: 'asc'},orders: [ 'asc', 'desc','']}"
          @edit-closed="editClosedEvent" @header-cell-click="headerCellClickEvent" @edit-disabled="editDisabledEvent"
          :edit-config="{
            trigger: 'dblclick',
            mode: 'srow',
            showStatus: true,
            icon: 'el-icon-s-tools',
          }"  @checkbox-all="selectAllEvent" @checkbox-change="selectChangeEvent">
            <vxe-column type="checkbox" width="40" :disabled="true"></vxe-column>

            <vxe-column field="name" sortable title="NAME" :edit-render="{ name: 'input', attrs: { type: 'text' } }" width="120">
            </vxe-column>
            <vxe-column field="addr" title="地址" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>
            <vxe-column field="len" title="变量长度" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>
            <vxe-column field="type" title="PLC变量类型" :edit-render="{}" width="180">
              <template #default="{ row }">
                <span>{{ plcTypeOptions[row.type] || '未定义的数据类型' }}</span>
              </template>
              <template #edit="{ row }">
                <vxe-select v-model="row.type" transfer>
                  <vxe-option v-for="(value, name) in plcTypeOptions" :key="value" :value="name" :label="value"></vxe-option>
                </vxe-select>
              </template>
            </vxe-column>
            <vxe-column field="addrHead" title="起始地址" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>
            <vxe-column field="addrNum" title="地址数量" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>

            <vxe-column field="value" title="value" ></vxe-column>

            <vxe-column title="操作">
              <template #default="{ row }">
                <div class="operation-cell">
                  <el-popover placement="top" width="180" v-model="row.visible">
                    <p>确定要删除这一行({{ row.id }})吗？</p>
                    <div style="text-align: right; margin: 0">
                      <el-button size="mini" type="text" @click="row.visible = false">取消</el-button>
                      <el-button type="primary" size="mini" @click="deleteButtonEvent([row]);row.visible = false;">确定</el-button>
                    </div>
                    <el-link slot="reference" type="danger" v-if="!checking">删除</el-link>
                  </el-popover>
                </div>
              </template>
            </vxe-column>
            <vxe-column field="comments" title="备注" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>
          </vxe-table>

        </el-collapse-item>
        <el-collapse-item name="3">
          <template slot="title">
            <div class="myHead">多项反馈</div>
          </template>
           <!-- rs   -->
          <el-row :gutter="5" class="form">
            <el-col :span="24">
              <div style="margin:10px;">
                地址/名称/备注:
                <el-input placeholder="地/名称/备注" v-model="requestParamsObjOfQS.name" @keyup.enter="getData" :disabled="loading || checking"> </el-input>
              </div>
            </el-col>
          </el-row>
          <TableOperationButtons style="margin:10px;" :loading="loading"
            :newButton="newButton" :deleteButton="deleteButton" :testButton="testButton"
            improtUrl="/svid/importCSV" exportUrl="/svid/exportCSV" improtUrlDisabled exportUrlDisabled>
          </TableOperationButtons>
          <el-alert :title="alertTitle" type="info" show-icon v-show="alertTitle">
          </el-alert>
          <vxe-table keep-source border resizable show-overflow ref="xTable2" class="vxe-table" empty-text="没有更多数据了！"
          :scroll-y="{ enabled: false }" :loading="loading" :data="tableDataOfQS"
          :sort-config="{trigger: 'cell',showIcon: true, defaultSort: {field: 'id', order: 'asc'},orders: [ 'asc', 'desc','']}"
          @edit-closed="editClosedEvent" @header-cell-click="headerCellClickEvent" @edit-disabled="editDisabledEvent"
          :edit-config="{
            trigger: 'dblclick',
            mode: 'srow',
            showStatus: true,
            icon: 'el-icon-s-tools',
          }"  @checkbox-all="selectAllEvent" @checkbox-change="selectChangeEvent">
            <vxe-column type="checkbox" width="40" :disabled="true"></vxe-column>

            <vxe-column field="name" sortable title="NAME" :edit-render="{ name: 'input', attrs: { type: 'text' } }" width="120">
            </vxe-column>
            <vxe-column field="addr" title="地址" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>
            <vxe-column field="len" title="变量长度" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>
            <vxe-column field="type" title="PLC变量类型" :edit-render="{}" width="180">
              <template #default="{ row }">
                <span>{{ plcTypeOptions[row.type] || '未定义的数据类型' }}</span>
              </template>
              <template #edit="{ row }">
                <vxe-select v-model="row.type" transfer>
                  <vxe-option v-for="(value, name) in plcTypeOptions" :key="value" :value="name" :label="value"></vxe-option>
                </vxe-select>
              </template>
            </vxe-column>
            <vxe-column field="addrHead" title="起始地址" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>
            <vxe-column field="addrNum" title="地址数量" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>

            <vxe-column field="value" title="value" ></vxe-column>

            <vxe-column title="操作">
              <template #default="{ row }">
                <div class="operation-cell">
                  <el-popover placement="top" width="180" v-model="row.visible">
                    <p>确定要删除这一行({{ row.id }})吗？</p>
                    <div style="text-align: right; margin: 0">
                      <el-button size="mini" type="text" @click="row.visible = false">取消</el-button>
                      <el-button type="primary" size="mini" @click="deleteButtonEvent([row]);row.visible = false;">确定</el-button>
                    </div>
                    <el-link slot="reference" type="danger" v-if="!checking">删除</el-link>
                  </el-popover>
                </div>
              </template>
            </vxe-column>
            <vxe-column field="comments" title="备注" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>
          </vxe-table>
        </el-collapse-item>
      </el-collapse>
    </div>
  </div>
</template>

<script>
// import { findTrtByName, setTrt, delTrts } from '@/api/request';
import TableOperationButtons from './common/TableOperationButtons.vue';

export default {
  name: 'TrTson',
  data() {
    return {
      showPanel: ['1', '2'],
      isAccordion: true,
      loading: false,
      checking: false,
      alertTitle: '',
      tableHeight: 500,
      tableDataOfRS: this.row.rs,
      tableDataOfQS: this.row.qs,
      requestParamsObjOfRS: {
        name: '',
        key: this.row.key,
        orderBy: {
          fieldName: 'name',
          fieldOrderType: 'asc',
        },
        page: {
          page: 1,
          size: 5,
          total: 0,
        },
      },
      requestParamsObjOfQS: {
        name: '',
        key: this.row.key,
        orderBy: {
          fieldName: 'name',
          fieldOrderType: 'asc',
        },
        page: {
          page: 1,
          size: 5,
          total: 0,
        },
      },
      newButton: {
        event: this.newButtonEvent,
      },
      deleteButton: {
        event: this.deleteButtonEvent,
        length: 0,
      },
      testButton: {
        clicked: false,
      },
    };
  },
  components: {
    TableOperationButtons,
  },
  props: {
    row: Object,
  },
  mounted() {
    this.getData(true);
  },
  methods: {
    getData(isChecking) {
      console.info('show row=', this.row);
      if (this.row == null) {
        this.row = {};
      }
      if (this.row.q === undefined || this.row.q === null) {
        this.row.q = {};
      }
      if (this.row.r === undefined || this.row.r === null) {
        this.row.r = {};
      }
      if (this.row.rs === undefined || this.row.rs === null) {
        this.row.rs = [];
      }
      if (this.row.qs === undefined || this.row.qs === null) {
        this.row.qs = [];
      }
      this.alertTitle = null;
      this.$refs.xTable1.clearCheckboxRow();
      const requestParamsObjR = JSON.parse(
        JSON.stringify(this.requestParamsObjOfRS),
      );
      delete requestParamsObjR.page.total;
      if (!isChecking) {
        this.loading = true;
      } else {
        this.loading = false;
      }
    },

    // 表格编辑完
    editClosedEvent({ row, column }) {
      const $table = this.$refs.xTable1;
      const field = column.property;
      // const cellValue = row[field];
      // 判断单元格值是否被修改
      if ($table.isUpdateByRow(row, field)) {
        if (row.isNew) {
          return;
        }
        this.saveData(row);
      }
    },

    //  保存数据
    saveData(row) {
      console.long('save row', row);
      const savaObj = {
        // 保存单个Trt对象
      };
      console.long('save savaObj', savaObj);
    },
    // 切换表格排序的规则
    headerCellClickEvent({
      column,
      // triggerResizable,
      // triggerSort,
      // triggerFilter,
    }) {
      // 如果触发了列的其他功能按钮
      if (column.sortable) {
        if (column.order) {
          this.requestParamsObjOfRS.orderBy = {
            fieldName: column.property,
            fieldOrderType: column.order,
          };
        } else {
          delete this.requestParamsObj.orderBy;
        }
        this.getData();
      }
    },
    editDisabledEvent({ row, column }) {
      console.log(row, column);
      // this.$XModal.message({ content: '禁止编辑', status: 'error' });
      this.$message({
        message: '监控状态下不能操作表格数据',
        type: 'warning',
        // duration: 999999,
      });
    },
    // 全选事件
    selectAllEvent({ records }) {
      this.multipleSelection = records;
      this.deleteButton.length = records.length;
      this.alertTitle = `已经选择 ${records.length} 了项`;
    },
    // 勾选事件
    selectChangeEvent({ records }) {
      this.multipleSelection = records;
      this.deleteButton.length = records.length;
      this.alertTitle = `已经选择 ${records.length} 了项`;
    },
    // 分页参数改变
    handlePageChange(page) {
      this.requestParamsObj.page = {
        page: page.currentPage,
        size: page.pageSize,
      };
      this.getData();
    },
    //  新建的操作
    async newButtonEvent() {
      const $table = this.$refs.xTable;
      const record = {
        isNew: true,
        comments: '',
        name: '',
      };
      const { row: newRow } = await $table.insertAt(record);
      await $table.setActiveCell(newRow, 'id');
    },
    // 删除表格数据
    deleteButtonEvent(rows) {
      const list = rows || this.multipleSelection;
      let data = [];
      if (list && list.length) {
        data = list.map((item) => item.name);
      }
      if (data.length) {
        this.loading = true;
      }
    },
    // 展开行的切换
    toggleExpandChangeEvent({ row }) {
      if (!row || !row.key) {
        this.$message({
          message: '保存成功本条数据后才能展开子表',
          type: 'error',
        });
      }
      return true;
    },
  },
  computed: {
    formatOptions() {
      return this.$store.state.formatOptions || {};
    },
    plcTypeOptions() {
      return this.$store.state.plcTypeOptions || {};
    },
    plcAddrOptions() {
      return this.GLOBAL.getPlcAddrOptions() || [];
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
.TrT-container {
  padding: 1rem;
  .form {
    // margin: 1rem 0;
    .el-input {
      width: 200px;
      display: inline-block;
      margin-left: 0.5rem;
    }
  }
  /deep/ .vxe-body--expanded-column {
    background-color: #e6f7ff;
  }
  .el-alert {
    margin-bottom: 1rem;
  }
}
.myHead{
  font-size: larger;
  margin: 10px;
  font-weight:bold;
  border-bottom-style: dotted;
  width: 100%;
}
</style>
